package com.github.mall.common.log.utils;

import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpUtil;
import com.github.mall.common.constant.enmus.CommontReturnEnums;
import com.github.mall.common.entity.SysLogEntity;
import lombok.experimental.UtilityClass;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@UtilityClass
public class SysLogUtils {
	public SysLogEntity getSysLog() {
		HttpServletRequest request = ((ServletRequestAttributes) Objects
			.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
		SysLogEntity sysLog = new SysLogEntity();
//		sysLog.setCreateBy(Objects.requireNonNull(getUsername()));
		sysLog.setType(String.valueOf(CommontReturnEnums.OK.getCode()));
		sysLog.setRemoteAddr(ServletUtil.getClientIP(request));
		sysLog.setRequestUri(URLUtil.getPath(request.getRequestURI()));
		sysLog.setMethod(request.getMethod());
		sysLog.setUserAgent(request.getHeader("user-agent"));
		sysLog.setParams(HttpUtil.toParams(request.getParameterMap()));
//		sysLog.setServiceId(getClientId());
		return sysLog;
	}

//	/**
//	 * 获取客户端
//	 *
//	 * @return clientId
//	 */
//	private String getClientId() {
//		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//		if (authentication instanceof OAuth2Authentication) {
//			OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
//			return auth2Authentication.getOAuth2Request().getClientId();
//		}
//		return null;
//	}
//
//	/**
//	 * 获取用户名称
//	 *
//	 * @return username
//	 */
//	private String getUsername() {
//		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//		if (authentication == null) {
//			return null;
//		}
//		return authentication.getName();
//	}

}
